import { useRef } from 'react';
import { loadMicroApp } from 'qiankun';
import { useMount, useUnmount } from 'ahooks';
import { customAlphabet } from 'nanoid';
import {history} from 'umi'

const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz', 10);
import routes from '../../config/routes'

function traverseRoutes (routes: any[], path: string) {
  for (let item of routes) {
    if (item.path === path) {
      return item.entry
    }
    if (item.routes && item.routes.length > 0) {
      let entry: any = traverseRoutes(item.routes, path)
      if (entry) {
        return entry
      }
    }
  }
  return ''
}
const MicroAppLayout = () => {
  
  const container = useRef(null);
  const containerID = useRef(nanoid(10));
  // const id = nanoid(10);
  const microApp: any = useRef(null);
  useMount(() => {
    const entry = traverseRoutes(routes, history.location.pathname)
    microApp.current = loadMicroApp(
      {
        name: `app${containerID.current}`,
        entry: entry,
        container: `#${containerID.current}`,
      },
      {
        sandbox: { strictStyleIsolation: true },
        singular: false,
      },
    );
  });

  useUnmount(() => {
    microApp.current.getStatus() === 'MOUNTED' ? microApp.current.unmount() : 0;
  });
  // if (isUrl(entry)) { return (<NotFound />) }
  return <div ref={container} id={containerID.current} />;
};

export default MicroAppLayout;
